package com.yygo.dao.hibernate;

import com.yygo.dao.BondDao;
import com.yygo.model.BondCompany;
import com.yygo.model.Dealer;
import com.yygo.model.LoanProduct;
import com.yygo.model.vo.BondCompanyVO;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by tiansha on 2015/8/8.
 */
@Repository("bondDao")
public class BondDaoHibernate extends GenericDaoHibernate<BondCompany, Long> implements BondDao {

    public BondDaoHibernate() {
        super(BondCompany.class);
    }

  public void generateChildTree(BondCompany bondCompany, BondCompanyVO bondCompanyVO){
    List<BondCompanyVO> bondCompanyVOs = new ArrayList<>();
    bondCompanyVO.setId(bondCompany.getId());
    bondCompanyVO.setName(bondCompany.getName());
    bondCompanyVO.setChildren(bondCompanyVOs);
    for(BondCompany bondCompany1: bondCompany.getChildren()){
      BondCompanyVO bondCompanyVO1 = new BondCompanyVO();
      bondCompanyVO1.setId(bondCompany1.getId());
      bondCompanyVO1.setName(bondCompany1.getName());
      bondCompanyVOs.add(bondCompanyVO1);
      generateChildTree(bondCompany1, bondCompanyVO1);
    }
    bondCompanyVO.setChildren(bondCompanyVOs);
  }

    @Override
    public BondCompany loadBond(Long id) {
        BondCompany bondCompany = get(id);
        Set<Long> ids = new HashSet<>();
        for (LoanProduct loanProduct : bondCompany.getLoanProducts()) {
            ids.add(loanProduct.getId());
        }

        bondCompany.setProductIds(ids);
        return bondCompany;
    }

  @Override
   public BondCompanyVO loadChildTree(Long id){
    BondCompany bondCompany = get(id);
    BondCompanyVO bondCompanyVO = new BondCompanyVO();

    generateChildTree(bondCompany, bondCompanyVO);
    return bondCompanyVO;
  }

    @Override
    public Set<Dealer> getDealers(Long bondId) {
        BondCompany bondCompany = get(bondId);
        for (Dealer dealer : bondCompany.getDealers()) {
            dealer.getId();
        }
        return bondCompany.getDealers();
    }

    @Override
    public BondCompany save(BondCompany bondCompany) {
        getSession().saveOrUpdate(bondCompany);
        // necessary to throw a DataIntegrityViolation and catch it in UserManager
        getSession().flush();
        return bondCompany;
    }

    @Override
    public BondCompany load(Long bondId) {
        BondCompany bondCompany = get(bondId);
        for (LoanProduct loanProduct : bondCompany.getLoanProducts()) {
            loanProduct.getId();
        }
        return bondCompany;
    }
}
